package com.gtallinone.server;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;

import com.gtallinone.client.GreetingService;

import com.gtallinone.client.GreetingServiceAsync;
import com.gtallinone.shared.FieldVerifier;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;

import java.lang.StringBuilder;


/**
 * The server side implementation of the RPC service.
 */
@SuppressWarnings("serial")
public class GreetingServiceImpl extends RemoteServiceServlet implements
		GreetingService {
	
	
	private Connection conn = null;
	private String status;
	private String url  = "jdbc:mysql://localhost/test"; 
	private String user = "root";
	private String pass = "root";
	
	private GreetingServiceAsync rpctoClient;
	

	public String greetServer(String input) throws IllegalArgumentException {
		// Verify that the input is valid. 
		if (!FieldVerifier.isValidName(input)) {
			// If the input is not valid, throw an IllegalArgumentException back to
			// the client.
			throw new IllegalArgumentException(
					"Name must be at least 4 characters long");
		}

		String serverInfo = getServletContext().getServerInfo();
		String userAgent = getThreadLocalRequest().getHeader("User-Agent");

		// Escape data from the client to avoid cross-site script vulnerabilities.
		input = escapeHtml(input);
		userAgent = escapeHtml(userAgent);

		return "Hello, " + input + "!<br><br>I am running " + serverInfo
				+ ".<br><br>It looks like you are using:<br>" + userAgent;
	}

	/**
	 * Escape an html string. Escaping data received from the client helps to
	 * prevent cross-site script vulnerabilities.
	 * 
	 * @param html the html string to escape
	 * @return the escaped string
	 */
	private String escapeHtml(String html) {
		if (html == null) {
			return null;
		}
		return html.replaceAll("&", "&amp;").replaceAll("<", "&lt;")
				.replaceAll(">", "&gt;");
	}
	
	/**
	 * 
	 * @param username
	 * @return
	 */
	public String getPassword(String username){
			String ans = null;
			try {
				System.out.println("error caught here01");

				Class.forName("com.mysql.jdbc.Driver").newInstance();
				System.out.println("error caught here02");

				conn = DriverManager.getConnection(url, user, pass);
				System.out.println("error caught here03");

			      System.out.println("Connected to database: ");
			     
				PreparedStatement ps = conn.prepareStatement("select password from user where username = \"" + username + "\"");
				ResultSet result = ps.executeQuery();
			
				while (result.next()) {
					ans = result.getString(1);
				}
				result.close();
				ps.close();
				conn.close();
			} catch (SQLException e) {
				System.err.println("Mysql Connection Error: "+conn);
				System.out.println("inside excpetion");
				e.printStackTrace();
				//NEVER catch exceptions like this
			} catch (InstantiationException e) {
				System.out.println("error caught here1");
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				System.out.println("error caught here2");

				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ClassNotFoundException e) {
				System.out.println("error caught here3");

				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		
			return ans;
	}
	
	public String authenticateUser(String username, String password) {
		//User user2 = new User();
		StringBuilder sb = new StringBuilder();
		String ans = null;
		try {
			Class.forName("com.mysql.jdbc.Driver").newInstance();
			conn = DriverManager.getConnection(url, user, pass);
			 
		      System.out.println("Connected to database: ");
		     
			PreparedStatement ps = conn.prepareStatement("select password from user where username = \"" + username  + "\"");
			ResultSet result = ps.executeQuery();
		
			while (result.next()) {
				/*
				sb.append("flag:login;");
				sb.append("username:");
				sb.append(result.getString(1));
				sb.append(",password:");
				sb.append(result.getString(2));
				sb.append(",");
				ans=sb.toString();
				System.out.println(result.getString(1));
				System.out.println(result.getString(2));*/
				ans = result.getString(1);
			}
			
			
			result.close();
			ps.close();
			conn.close();
		} catch (SQLException e) {
			System.err.println("Mysql Connection Error: "+conn);
			System.out.println("inside excpetion");
			e.printStackTrace();
			//NEVER catch exceptions like this
		} catch (InstantiationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return ans;
	}
	
	public ArrayList getPhiloAnnouncement(){
		//User user2 = new User();
		StringBuilder sb = new StringBuilder();
		ArrayList ans = new ArrayList();
		try {
			Class.forName("com.mysql.jdbc.Driver").newInstance();
			conn = DriverManager.getConnection(url, user, pass);
		      System.out.println("Connected to database: ");
			PreparedStatement ps = conn.prepareStatement("post_date, select title, username from announcements,post_ann where ann_type = \"philo\" and announcements.ann_index = post_ann.ann_index");
			ResultSet result = ps.executeQuery();
		
			while (result.next()) {
				ans.add(result.getTime(1));
				ans.add(result.getString(2));
				ans.add(result.getString(3));

			}
			
			
			result.close();
			ps.close();
			conn.close();
		} catch (SQLException e) {
			System.err.println("Mysql Connection Error: "+conn);
			System.out.println("inside excpetion");
			e.printStackTrace();
			//NEVER catch exceptions like this
		} catch (InstantiationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return ans;
	}
}
